package com.echoplots.jpa.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
@EnableJpaRepositories(basePackages = "com.echoplots.jpa.slavedao",
        entityManagerFactoryRef = "localContainerEntityManagerFactoryBeanSlave",
        transactionManagerRef = "platformTransactionManagerSlave")
public class SlaveJpaConfig {
    @Autowired
    @Qualifier(value = "dsSlave")
    DataSource dsSlave;

    @Autowired
    JpaProperties jpaProperties;

    @Bean
    LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBeanSlave(EntityManagerFactoryBuilder builder){
        return builder.dataSource(dsSlave)
                .properties(jpaProperties.getProperties())
                .packages("com.echoplots.jpa.entity")
                .persistenceUnit("puSlave")
                .build();

    }

    @Bean
    PlatformTransactionManager platformTransactionManagerSlave(EntityManagerFactoryBuilder builder){
        LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = localContainerEntityManagerFactoryBeanSlave(builder);
        return new JpaTransactionManager(localContainerEntityManagerFactoryBean.getObject());
    }
}
